package com.kevin.controller;

import com.kevin.utils.Result;
import groovy.util.logging.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kevin
 * @ClassName: FileController
 */
@CrossOrigin(origins = "*", maxAge = 3600) // 允许所有域名访问
@Controller
@Slf4j
public class TestController {
    @Autowired
    ResourceLoader resourceLoader;

    @RequestMapping("/up")
    public String index() {
        return "up";
    }

    /**
     * @Title: uploadFile
     * @Description: 上传文件
     * @author kevin
     */
    @PostMapping("/uploadExcel")
    @ResponseBody
    public Result uploadExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        Result result = new Result();
        // 判断file数组不能为空并且长度大于0
        if (file != null) {
            MultipartFile f = file;
            Boolean bool = ImportExcel.checkFile(file);
            if(!bool){
                result.setMsg("empty");
                return result;
            }
            //工具类在下面
            HashMap<String, ArrayList<String[]>> hashMap = null;
            try {
                hashMap = ImportExcel.analysisFile(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
            ArrayList<String[]> arrayList = hashMap.get("OK");
            result.setData(arrayList);
        }
        return result;
    }

    @GetMapping("/downloadExcel")
    @ResponseBody
    public void downloadExcel(HttpServletResponse response) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        Resource resource = resourceLoader.getResource("classpath:test.xlsx");
        try {
            String filename = new String(resource.getFilename().getBytes(), "ISO8859-1");
            // 设置文件输出类型
            response.setContentType("application/octet-stream");
            // 设置文件输出名称
            response.setHeader("Content-disposition", "attachment; filename=" + "\"" + filename + "\"");
            // 获取文件的长度
            response.setHeader("Content-Length", String.valueOf(resource.getFile().length()));
            // 获取输入流
            bis = new BufferedInputStream(resource.getInputStream());
            // 获取输出流
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            // 关闭流
            bis.close();
            bos.flush();
            bos.close();
        } catch (FileNotFoundException e) {
            System.out.println("文件未找到");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("IO异常");
            e.printStackTrace();
        }
    }

    @GetMapping("/downloadData")
    public void export(HttpServletResponse res) {
        try {
            // 第一步，创建一个webbook，对应一个Excel文件
            XSSFWorkbook wb = new XSSFWorkbook();
            String excelName="测试字典";
            //生成一个表格
            Sheet sheet = wb.createSheet(excelName);
            // 第三步，在sheet中添加表头第0行
            Row row = sheet.createRow(0);
            // 第四步，创建单元格，并设置值表头 设置表头居中
            CellStyle style = wb.createCellStyle();
            style.setAlignment(CellStyle.ALIGN_CENTER); // 创建一个居中格式
            Cell cell = row.createCell(0);
            cell.setCellStyle(style);
            cell.setCellValue("字典列表导出结果集");
            List list=new ArrayList();
            Map map1=new HashMap();
            map1.put("name","tapxinhuan");
            map1.put("sex","男");
            map1.put("age","18");
            list.add(map1);
            list.add(map1);
            list.add(map1);
            res.addHeader("Content-Disposition", "attachment;filename="+new String(excelName.getBytes("gb2312"), "ISO8859-1" )+".xlsx");
            this.insertData(wb, sheet, row, list, res.getOutputStream(), new String[]{"名称", "代码", "序号"});
        } catch (Exception e) {
            System.out.println(e);
        }

    }

    /**
     * 导入数据到表格中
     *
     * @param wb     execl文件
     * @param sheet  表格
     * @param row    表格行
     * @param record 要导出的数据
     * @param out    输出流
     */
    private void insertData(Workbook wb, Sheet sheet, Row row, List record,
                            OutputStream out, String[] title) {
        try {
            row = sheet.createRow(1);
            for (int i = 0; i < title.length; i++) {
                row.createCell(i).setCellValue(title[i]);
            }
            for (int i = 0; i < record.size(); i++) {
                row = sheet.createRow(i + 2);
                Object data = record.get(i);
                Map map = (Map) data;
                row.createCell(0).setCellValue(map.get("name").toString());
                row.createCell(1).setCellValue(map.get("sex").toString());
                row.createCell(2).setCellValue(map.get("age").toString());
            }
            //合并单元格，前面2位代表开头结尾行，后面2位代表开头结尾列
            CellRangeAddress region = new CellRangeAddress(0, 0, 0, title.length - 1);
            sheet.addMergedRegion(region);
            wb.write(out);
            ByteArrayOutputStream bos=new ByteArrayOutputStream();
            wb.write(bos);
            out.flush();
            out.close();
            wb.close();
        } catch (Exception e) {
            System.out.println("导出失败");
        }
    }
}
